package com.xumt.hwHMSdemo;

import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;

import android.Manifest;
import android.content.Intent;
import android.content.IntentSender;
import android.content.pm.PackageManager;
import android.location.Location;
import android.os.Build;
import android.os.Bundle;
import android.os.Looper;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

import com.huawei.hmf.tasks.OnFailureListener;
import com.huawei.hmf.tasks.OnSuccessListener;
import com.huawei.hmf.tasks.Task;
import com.huawei.hms.common.ApiException;
import com.huawei.hms.common.ResolvableApiException;
import com.huawei.hms.location.FusedLocationProviderClient;
import com.huawei.hms.location.LocationAvailability;
import com.huawei.hms.location.LocationCallback;
import com.huawei.hms.location.LocationRequest;
import com.huawei.hms.location.LocationResult;
import com.huawei.hms.location.LocationServices;
import com.huawei.hms.location.LocationSettingsRequest;
import com.huawei.hms.location.LocationSettingsResponse;
import com.huawei.hms.location.LocationSettingsStatusCodes;
import com.huawei.hms.location.SettingsClient;
//import com.huawei.logger.LocationLog;
public class Locationkit extends AppCompatActivity {

    public static final String TAG = "HuaweiPushActivity";
    private Double longitude;
    private Double lititude;
    private FusedLocationProviderClient fusedLocationProviderClient;
    // 定位请求信息对象
    private LocationRequest mLocationRequest;
//    private LocationCallback mLocationCallback;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_locationkit);



        Button button = (Button) findViewById(R.id.nearby);
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                nearbysearch();
            }


        });

        // Android SDK<=28 所需权限动态申请
        if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.P) {
            Log.i("TAG", "android sdk <= 28 Q");
            if (ActivityCompat.checkSelfPermission(this,
                    Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED
                    && ActivityCompat.checkSelfPermission(this,
                    Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
                String[] strings =
                        {Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION};
                ActivityCompat.requestPermissions(this, strings, 1);
            }
        } else {
            // Android SDK>28 所需权限动态申请，需添加“android.permission.ACCESS_BACKGROUND_LOCATION”权限
            if (ActivityCompat.checkSelfPermission(this,
                    Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED
                    && ActivityCompat.checkSelfPermission(this,
                    Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED
                    && ActivityCompat.checkSelfPermission(this,
                    "android.permission.ACCESS_BACKGROUND_LOCATION") != PackageManager.PERMISSION_GRANTED) {
                String[] strings = {android.Manifest.permission.ACCESS_FINE_LOCATION,
                        android.Manifest.permission.ACCESS_COARSE_LOCATION,
                        "android.permission.ACCESS_BACKGROUND_LOCATION"};
                ActivityCompat.requestPermissions(this, strings, 2);
            }
        }
//        getMyLoction();


        // 定位交互接入对象


        fusedLocationProviderClient = LocationServices.getFusedLocationProviderClient(this);
        SettingsClient settingsClient = LocationServices.getSettingsClient(this);
        mLocationRequest = new LocationRequest();
        mLocationRequest.setInterval(10000);
        mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
        LocationSettingsRequest.Builder builder = new LocationSettingsRequest.Builder();
        builder.addLocationRequest(mLocationRequest);
        LocationSettingsRequest locationSettingsRequest = builder.build();
// 检查设备定位设置
        settingsClient.checkLocationSettings(locationSettingsRequest)
                // 检查设备定位设置接口成功监听回调
                .addOnSuccessListener(new OnSuccessListener<LocationSettingsResponse>() {
                    @Override
                    public void onSuccess(LocationSettingsResponse locationSettingsResponse) {
                        // 设置满足定位条件，再发起位置请求
                        try {
                            Task<Location> lastLocation = fusedLocationProviderClient.getLastLocation();

                            lastLocation.addOnSuccessListener(new OnSuccessListener<Location>() {
                                @Override
                                public void onSuccess(Location location) {
                                    if (location == null) {
                                        Log.i(TAG, "getLastLocation onSuccess location is null");
                                        return;
                                    }
                                    longitude=location.getLongitude();
                                    lititude=location.getLatitude();
                                    TextView thisjingdu=findViewById(R.id.one);
                                    thisjingdu.setText(longitude.toString());
                                    TextView thisweidu=findViewById(R.id.two);
                                    thisweidu.setText(lititude.toString());
                                    Log.i(TAG, "getLastLocation onSuccess location[Longitude,Latitude]:"
                                            + location.getLongitude() + "," + location.getLatitude());
                                    return;
                                }
                            }).addOnFailureListener(new OnFailureListener() {
                                @Override
                                public void onFailure(Exception e) {
                                    if (e instanceof ResolvableApiException) {
                                        ResolvableApiException apiException = (ResolvableApiException) e;
                                        Log.e(TAG, "getLastLocation onFailure:" + apiException.getStatusCode());
                                        try {
                                            apiException.startResolutionForResult(Locationkit.this, 2009);
                                        } catch (IntentSender.SendIntentException ex) {
                                            ex.printStackTrace();
                                        }
                                    } else {
                                        Log.e(TAG, "getLastLocation onFailure:" + e.getMessage());
                                    }
                                }
                            });
                        } catch (Exception e) {
                            Log.e(TAG, "getLastLocation exception:" + e.getMessage());
                        }
//                        LocationCallback mLocationCallback;
//                        mLocationCallback = new LocationCallback() {
//                            @Override
//                            public void onLocationResult(LocationResult locationResult) {
//                                if (locationResult != null) {
//                                    // 处理位置回调结果
//                                    Log.i(TAG, "getLastLocation onSuccess location[Longitude,Latitude]1:"+locationResult.getLocations());
//                                    Log.i(TAG, "getLastLocation onSuccess location[Longitude,Latitude]2:"+locationResult.getHWLocationList());
//                                    Log.i(TAG, "getLastLocation onSuccess location[Longitude,Latitude]3:"+locationResult.getLastHWLocation());
//                                    Log.i(TAG, "getLastLocation onSuccess location[Longitude,Latitude]4:"+locationResult.getLastLocation());
//                                }
//                            }
//                        };
                    }
                })
                // 检查设备定位设置接口失败监听回调
                .addOnFailureListener(new OnFailureListener() {
                    @Override
                    public void onFailure(Exception e) {
                        // 设置不满足定位条件
                        int statusCode = ((ApiException) e).getStatusCode();
                        switch (statusCode) {
                            case LocationSettingsStatusCodes.RESOLUTION_REQUIRED:
                                try {
                                    ResolvableApiException rae = (ResolvableApiException) e;
                                    // 调用startResolutionForResult可以弹窗提示用户打开相应权限
                                    rae.startResolutionForResult(Locationkit.this, 0);
                                } catch (IntentSender.SendIntentException sie) {
                                    // ...
                                }
                                break;
                        }
                    }
                });


        // 获取最后的已知位置
        Task<Location> task = fusedLocationProviderClient.getLastLocation()
                // 获取最后的已知位置成功监听回调
                .addOnSuccessListener(new OnSuccessListener<Location>() {
                    @Override
                    public void onSuccess(Location location) {
                        if (location == null) {
                            return;
                        }
                        // 成功时Location对象处理逻辑
                        // ...
                    }
                })
                // 获取最后的已知位置失败监听回调
                .addOnFailureListener(new OnFailureListener() {
                    @Override
                    public void onFailure(Exception e) {
                        // ...
                    }
                });


    }

    public void nearbysearch(){
        Intent intent = new Intent(this, NearbySearchActivity.class);
        TextView thisjingdu=findViewById(R.id.one);
        String longitude1=thisjingdu.getText().toString();

        TextView thisweidu=findViewById(R.id.two);
        String lititude1=thisweidu.getText().toString();
        intent.putExtra(NearbySearchActivity.Longitude,Double.parseDouble(longitude1));
        intent.putExtra(NearbySearchActivity.Lititude, Double.parseDouble(lititude1));

        startActivity(intent);
    }

//    private void getMyLoction() {
//
//        fusedLocationProviderClient = LocationServices.getFusedLocationProviderClient(this);
//        SettingsClient settingsClient = LocationServices.getSettingsClient(this);
//        LocationSettingsRequest.Builder builder = new LocationSettingsRequest.Builder();
//        mLocationRequest = new LocationRequest();
//        builder.addLocationRequest(mLocationRequest);
//        LocationSettingsRequest locationSettingsRequest = builder.build();
////检查设备定位设置
//        settingsClient.checkLocationSettings(locationSettingsRequest)
//                .addOnSuccessListener(new OnSuccessListener<LocationSettingsResponse>() {
//                    @Override
//                    public void onSuccess(LocationSettingsResponse locationSettingsResponse) {
//                        //设置满足定位条件，再发起位置请求
//                        fusedLocationProviderClient
//                                .requestLocationUpdates(mLocationRequest, mLocationCallback, Looper.getMainLooper())
//                                .addOnSuccessListener(new OnSuccessListener<Void>() {
//                                    @Override
//                                    public void onSuccess(Void aVoid) {
//                                        //接口调用成功的处理
//                                        Log.i("TAG", "onSuccess: " + aVoid);
//                                    }
//                                });
//                    }
//                });
//    }
}
